<?php
namespace Home\Controller;
use Think\Controller;
class TestController extends Controller{
	public function _initialize(){
		ini_set('max_execution_time', '0');
		header("Content-type: text/html; charset=utf-8");
	}
    /**
     * 支持的语种
     * var ArrayAccess
     */
    private static $Lang = Array (
    		'auto' => '自动检测',
    		'ara' => '阿拉伯语',
    		'de' => '德语',
    		'ru' => '俄语',
    		'fra' => '法语',
    		'kor' => '韩语',
    		'nl' => '荷兰语',
    		'pt' => '葡萄牙语',
    		'jp' => '日语',
    		'th' => '泰语',
    		'wyw' => '文言文',
    		'spa' => '西班牙语',
    		'el' => '希腊语',
    		'it' => '意大利语',
    		'en' => '英语',
    		'yue' => '粤语',
    		'zh' => '中文'
    );
    public function pullHtmlPushDir(){
//---------------------Begin-------如果全部开启语言请开启此处---------//
    	$model='Home';
    	$Path = APP_PATH.$model."/View/*";
    	$dirs = glob($Path); 
    	foreach ($dirs as $key=>$vo){
    		foreach (glob($vo.'/*.html') as $vi){
		    	set_time_limit(0);
		    	echo $vi;
		    	echo "<br/>";
		    	//读取
		    	$myfile = fopen($vi, "r+") or die("Unable to open file!-1(21行错误)");
				while(!feof($myfile)) {
					//单行查找,筛选中文
					$strAtr = $this->filterNotZh(fgets($myfile));
					if($strAtr != null){
						foreach ($strAtr as $k=>$str){
							$time = substr(time(),-4);
							//写入zh-en.php语言包
							$key = $this->saveEntrance($str,'zh',false,'Home','Lang','zh-cn',$time);
		 					//写入en-us.php语言包
// 							sleep(3);
							$this->saveEntrance($str,'zh','en','Home','Lang','en-us',$time);
// 							sleep(3);
// 							$this->saveEntrance($str,'zh','jp','Home','Lang','jp-jp',$time);
// // 							sleep(3);
// 							$this->saveEntrance($str,'zh','ru','Home','Lang','ru-ru',$time);
// // 							sleep(3);
// 							$this->saveEntrance($str,'zh','yue','Home','Lang','yue-yue',$time);
// 							sleep(3);
							$item[strlen($str)][$key]=$str;
						}
					}
				}
				fclose($myfile);
				$r = $this->replaceFile($vi,$item);
    		}
    	}
//-----------------------end---------------------//

//-----------------------begin-------单页翻译-----------//
//     	$dir = "D:/WWW/hpgj/App/Home/View/test/index.html";
//     	set_time_limit(0);
//     	//读取
//     	$myfile = fopen($dir, "r+") or die("Unable to open file!-2(25行错误)");
// 		while(!feof($myfile)) {
// 			//单行查找,筛选中文
// 			$strAtr = $this->filterNotZh(fgets($myfile));
// 			if($strAtr != null){
// 				foreach ($strAtr as $k=>$str){
// 							$time = substr(time(),-4);
// 							//写入zh-en.php语言包
// 							$key = $this->saveEntrance($str,'zh',false,'Home','Lang','zh-cn',$time);
// 		 					//写入en-us.php语言包
// // 							sleep(3);
// 							$this->saveEntrance($str,'zh','en','Home','Lang','en-us',$time);
// // 							sleep(3);
// 							$this->saveEntrance($str,'zh','jp','Home','Lang','ja-jp',$time);
// // 							sleep(3);
// 							$this->saveEntrance($str,'zh','ru','Home','Lang','ru-ru',$time);
// // 							sleep(3);
// 							$this->saveEntrance($str,'zh','yue','Home','Lang','zh-tw',$time);
// // 							sleep(3);
// 							$item[strlen($str)][$key]=$str;
// 				}
// 			}
// 		}
// 		fclose($myfile);
// 		$r = $this->replaceFile($dir,$item);
//-----------------------end---------------------//
    }
    /**
     * 根据替换信息替换
     * @param Path $dir 路径
     * @param Array $replaceName 需要替换的文本
     */
    private function replaceFile($dir,$replaceName=array()){
    	//读取
    	$myfile = fopen($dir, "r+") or die("Unable to open file!-3(71行错误)");
    	$read = fread($myfile,filesize($dir));
    	//查找并且替换
    	krsort($replaceName);
    	foreach ($replaceName as $key=>$vo){
    		foreach ($vo as $key=>$vi){
    			$arr[$key] = $vi;
    		}
    	}
    	foreach ($arr as $key=>$vo){
    		if($vo == "暂无" || $vo =="//"  ||$vo == "<!--" ||$vo=='虚拟网' ||$vo=="微软雅黑" ||$vo=="本网站"){
    			continue;
    		}
     		$read = str_replace($vo,"{\$Think.lang.".$key."}",$read);
  //  		$read = str_replace($vo,"L(".$key.")",$read);
    		echo $vo."------"."{\$Think.lang.".$key."}"."------Success";
    		echo "<br/>";
    		ob_flush();
    		ob_clean();
    	}
    	fclose($myfile); 
    	//重新写入文件
    	$myfile = fopen($dir, "w") or die("Unable to open file!-4(92行错误)");
    	$write = fwrite($myfile, $read);
    	fclose($myfile);
    }
    /**
     * 过滤非中文字符
     * @param String $str 查找字符串
     * @return string 返回中文
     */
    private function filterNotZh($str){
//     	$str = "ddddvvv(,中文.)dfdsfds字啊 啊符啊.";
    	//把GB2312编码转化为 UTF-8编码
//     	$str = mb_convert_encoding($str, 'UTF-8', 'GB2312');
    	//正则匹配
    	preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $str, $matches);
    	//把匹配到的数组连接为字符串
//     	$str = implode('', $matches[0]);
    	//中文字符去重
//     	$str = str_split($str,3);
     	$str = array_unique($matches[0]);
//     	$str = implode($str);
    	//把UTF-8编码转化为 GB2312编码
//     	$str = mb_convert_encoding($str, 'GB2312', 'UTF-8');
    	return $str;
    }
    /**
     * 获取支持的语种
     * return array 返回支持的语种
    */
   private static function getLang() {
    	return self::$Lang;
    }
    /**
     * 执行文本翻译
     *
     * @param string $text
     *        	要翻译的文本
     * @param string $from
     *        	原语言语种 默认:中文
     * @param string $to
     *        	目标语种 默认:英文
     *        	return boolean string 翻译失败:false 翻译成功:翻译结果
     *
     */
   private  function exec($text,$from,$to) {
   		$url = "http://fanyi.baidu.com/v2transapi?from=".$from."&to=".$to."&query=".$text;
	   	$ch = curl_init();
	   	curl_setopt($ch, CURLOPT_URL,$url);
	   	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	   	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	   	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	   	$result = curl_exec($ch);
	   	curl_close ($ch);
// 	   	return $result;
//     	$url = "http://fanyi.baidu.com/v2transapi";
//     	$data = array (
//     			'from' => $from,
//     			'to' => $to,
//     			'query' => $text
//     	);
//     	$data = http_build_query ( $data );
//     	$ch = curl_init ();
//     	curl_setopt ( $ch, CURLOPT_URL, $url );
//     	curl_setopt ( $ch, CURLOPT_REFERER, "http://fanyi.baidu.com" );
//     	curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:37.0) Gecko/20100101 Firefox/37.0' );
//     	curl_setopt ( $ch, CURLOPT_HEADER, 0 );
//     	curl_setopt ( $ch, CURLOPT_POST, 1 );
//     	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
//     	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
//     	curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 );
//     	$result = curl_exec ( $ch );
//     	curl_close ( $ch );
    	$result = json_decode ( $result, true );
    	if (isset ( $result ['error'] )) {
    		return false;
    	}
    	return $result ['trans_result'] ['data'] ['0'] ['dst'];
    }
    /**
     * 翻译->内部调用写入方法
     * @param String $str 写入文本
     * @param String $lang 写入原始语言
     * @param String $newLang 转换语言
     * @param String $model   写入模块地址
     * @param String $folder  写入二级文件夹
     * @param String $fileName写入文件名称
     * @return boolean 
     */
    
    private function saveEntrance($str,$lang,$newLang=false,$model,$folder,$fileName,$time) {
    	$PingYing = $this->getPingYingObj();
    	if($newLang){
    		$newLangs = $this->exec($str, $lang, $newLang);
			while($newLangs == false){
				sleep(60);
				$newLangs = $this->exec($str, $lang, $newLang);
				if($newLangs !=false ){
					break;
				}
			} 
    		$r = $this->setConfigByFileName ($model,$folder, $fileName,
    				array (
    						"__".strtoupper($PingYing::getShortPinyin(trim($str))).$time."__"=>$newLangs
    				)
    		);
    	}else{
    		$r = $this->setConfigByFileName ($model, $folder, $fileName,
    				array (
    						"__".strtoupper($PingYing::getShortPinyin(trim($str))).$time."__"=>$str
    				)
    		);
    	}
    	return $r;
    		
    }
    /**
     * 写入文件
     * @param String $model   写入模块地址
     * @param String $folder  写入二级文件夹
     * @param String $fileName写入文件名称
     * @param Array $arrData写入信息
     * @return boolean 
     */
    private function setConfigByFileName($model,$folder, $fileName, $arrData) {
    	$model or $model = MODULE_NAME;
    	$fileName or die ( '没有文件名' );
//     	$savePath = str_replace ( 'Common', $model, CONF_PATH . $fileName . '.php' );
    	$savePath = APP_PATH.$model."/".$folder."/".$fileName.".php";
    	if (file_exists ( $savePath )) {
    		$return = require $savePath;
    	}
//     	else{
//     		mkdir(APP_PATH.$model."/".$folder);
//     		$return = require $savePath;
//     	}
    	// 数据为空的时候,则读取文件信息
    	if (empty ( $arrData )) {
    		return $return;
    	}
    	
// 		$key = key($arrData);
// 		$value = $arrData[key($arrData)];
		
// 		if(array_key_exists($key,$return)){
// 			if(!in_array($value, $return)){
// 				unset($arrData);
// 				$arrData[$key.rand('1000', '9999').'_'] = $value;
// 				$key = key($arrData);
// 			}
// 		}
		//$arrData = $this->Gogogo($arrData, $return);
    	$return = array_merge ( ( array ) $return, $arrData );
    	$str = var_export ( $return, true );
    	$str = '<?php return 
//--------下方为系统自动生成,请谨慎修改---------//
    			' . $str . '
    			;';
    	file_put_contents ( $savePath, $str );
    	return key($arrData);
    }
    /**
     * 获取PingYing Obj
     * @return \Pinyin
     */
    private function getPingYingObj(){
    	require_once(APP_PATH.'/Common/Common/Pinyin.php');
//     	require_once('Pinyin.php');
    	$PingYing = new \Pinyin();
    	return $PingYing;
    }
//     public function test(){
//     	$arrData = array("__M__T_"=>'买',"__M__T_"=>'卖');
//     	$return = array("__M__"=>'买',"__M__T_"=>'卖',"__M__T_"=>'卖');
//     	dump($this->Gogogo($arrData, $return));
//     }
    
	private function Gogogo($arrData, $return, $key = '') {
		$r  =  array_intersect($return,$arrData);
		$key = ! empty ( $key ) ? $key : key ( $arrData );
		$value = $arrData [$key];
		if (array_key_exists ( $key, $return )) {
			if (! in_array ( $value, $return )) {
				unset ( $arrData [$key] );
				$key .= 'T_';
				$arrData [$key] = $value;
				$return  [$key] = $value;
				return $this->Gogogo ( $arrData, $return, $key );
			}else{
				return $r;
			}
		}  
		return $arrData;
	}
}
